<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加竞赛成绩</el-button>
    <el-table :data="competitions" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="competitionName" label="竞赛名称" />
      <el-table-column prop="level" label="竞赛级别" width="100" />
      <el-table-column prop="category" label="竞赛类别" width="80" />
      <el-table-column prop="prize" label="获奖等级" width="100" />
      <el-table-column prop="isTeam" label="是否团队赛" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isTeam ? 'success' : 'info'">
            {{ scope.row.isTeam ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleInTeam" label="团队角色" width="120" />
      <el-table-column prop="score" label="得分" width="80">
        <template #default="scope">
          {{ scope.row.score ? Number(scope.row.score).toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="竞赛成绩" @close="resetForm" width="600px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="竞赛名称" prop="competitionName">
          <el-input v-model="formData.competitionName" placeholder="请输入竞赛名称" />
        </el-form-item>
        
        <el-form-item label="竞赛级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择级别" style="width: 100%">
            <el-option label="国家级" value="国家级" />
            <el-option label="省级" value="省级" />
            <el-option label="市级" value="市级" />
            <el-option label="校级" value="校级" />
            <el-option label="CCF" value="CCF" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="竞赛类别" prop="category">
          <el-select v-model="formData.category" placeholder="请选择类别" style="width: 100%">
            <el-option label="A1" value="A1" />
            <el-option label="A2" value="A2" />
            <el-option label="A3" value="A3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="获奖等级" prop="prize">
          <el-select v-model="formData.prize" placeholder="请选择获奖等级" style="width: 100%">
            <el-option label="一等奖" value="一等奖" />
            <el-option label="二等奖" value="二等奖" />
            <el-option label="三等奖" value="三等奖" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="是否团队赛" prop="isTeam">
          <el-radio-group v-model="formData.isTeam">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="formData.isTeam" label="团队中角色" prop="roleInTeam">
          <el-input v-model="formData.roleInTeam" placeholder="请输入在团队中的角色" />
        </el-form-item>
        
        <el-form-item v-if="previewScore > 0" label="预计得分">
          <el-tag type="success" size="large">{{ previewScore.toFixed(2) }} 分</el-tag>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'CompetitionsModule',
  props: {
    studentId: { type: Number, required: true }
  },
  data() {
    return {
      competitions: [],
      dialogVisible: false,
      formData: {
        id: null,
        studentId: null,
        competitionName: '',
        level: '',
        category: '',
        prize: '',
        isTeam: false,
        roleInTeam: ''
        // score字段由后端自动计算
      },
      rules: {
        competitionName: [{ required: true, message: '请输入竞赛名称', trigger: 'blur' }],
        level: [{ required: true, message: '请选择竞赛级别', trigger: 'change' }],
        category: [{ required: true, message: '请选择竞赛类别', trigger: 'change' }],
        prize: [{ required: true, message: '请选择获奖等级', trigger: 'change' }],
        isTeam: [{ required: true, message: '请选择是否团队赛', trigger: 'change' }]
      },
      previewScore: 0
    }
  },
  watch: {
    studentId: {
      immediate: true,
      handler(newVal) {
        if (typeof newVal === 'number' && !isNaN(newVal)) {
          this.loadData()
        } else {
          this.competitions = []
        }
      }
    },
    'formData.level': 'calculatePreviewScore',
    'formData.category': 'calculatePreviewScore',
    'formData.prize': 'calculatePreviewScore',
    'formData.isTeam': 'calculatePreviewScore'
  },
  methods: {
    calculatePreviewScore() {
      const { level, category, prize, isTeam } = this.formData
      
      if (!level || !category || !prize) {
        this.previewScore = 0
        return
      }
      
      let baseScore = 0
      
      // 根据竞赛级别确定基础分值
      switch (level) {
        case '国家级':
          baseScore = 100
          break
        case '省级':
          baseScore = 80
          break
        case '市级':
          baseScore = 60
          break
        case '校级':
          baseScore = 40
          break
        case 'CCF':
          baseScore = 90
          break
        default:
          baseScore = 0
      }
      
      // 根据竞赛类别调整分值
      switch (category) {
        case 'A1':
          baseScore *= 1.0
          break
        case 'A2':
          baseScore *= 0.8
          break
        case 'A3':
          baseScore *= 0.6
          break
      }
      
      // 根据获奖等级调整分值
      switch (prize) {
        case '一等奖':
          baseScore *= 1.0
          break
        case '二等奖':
          baseScore *= 0.7
          break
        case '三等奖':
          baseScore *= 0.5
          break
      }
      
      // 团队赛额外加分
      if (isTeam) {
        baseScore *= 1.1
      }
      
      this.previewScore = Math.round(baseScore * 100) / 100
    },
    async loadData() {
      try {
        const res = await axios.get(`/api/competitions/student/${this.studentId}`)
        this.competitions = res.data || []
      } catch (e) {
        this.$message.error('加载竞赛成绩失败')
      }
    },
    openAddDialog() {
      this.formData = {
        id: null,
        studentId: this.studentId,
        competitionName: '',
        level: '',
        category: '',
        prize: '',
        isTeam: false,
        roleInTeam: ''
        // score字段由后端自动计算
      }
      this.previewScore = 0
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId }
      this.dialogVisible = true
    },
    async submit() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        // 构建提交数据
        const submitData = {
          ...this.formData,
          roleInTeam: this.formData.isTeam ? this.formData.roleInTeam : null
        }

        let res
        if (this.formData.id) {
          res = await axios.put('/api/competitions', submitData)
        } else {
          res = await axios.post('/api/competitions', submitData)
        }

        if (res.data.code === 200 || res.data > 0) {
          this.$message.success(this.formData.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error(res.data.message || (this.formData.id ? '更新失败' : '添加失败'))
        }
      } catch (e) {
        this.$message.error('提交失败')
      }
    },
    async handleDelete(id) {
      try {
        await axios.delete(`/api/competitions/${id}`)
        this.$message.success('删除成功')
        await this.loadData()
        this.$emit('save-success')
      } catch (e) {
        this.$message.error('删除失败')
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        id: null,
        studentId: this.studentId,
        competitionName: '',
        level: '',
        category: '',
        prize: '',
        isTeam: false,
        roleInTeam: ''
        // score字段由后端自动计算
      }
      this.previewScore = 0
    }
  }
}
</script>
